import {
  orderStatistics,
  salesTop10Report,
  turnoverStatistics,
  userStatistics,
} from '@/services/swagger/reportController';
import { Card, Col, DatePicker, Row, Spin } from 'antd';
import type { Dayjs } from 'dayjs';
import moment from 'dayjs'; // 改用 dayjs
import 'dayjs/locale/zh-cn'; // 可选：设置中文
import advancedFormat from 'dayjs/plugin/advancedFormat'; // 如有需要扩展功能
import ReactECharts from 'echarts-for-react';
import React, { useEffect, useState } from 'react';

moment.extend(advancedFormat); // 启用插件
const RevenuePage: React.FC = () => {
  const [loading, setLoading] = useState<boolean>(false);
  const [timeRange, setTimeRange] = useState<[Dayjs, Dayjs] | null>(null);

  // 营业额数据
  const [turnoverData, setTurnoverData] = useState<{ dates: string[]; amounts: number[] }>({
    dates: [],
    amounts: [],
  });

  // 用户统计数据
  const [userData, setUserData] = useState<{
    dates: string[];
    users: number[];
    newUsers: number[];
  }>({
    dates: [],
    users: [],
    newUsers: [],
  });

  // 订单统计数据
  const [orderData, setOrderData] = useState<{
    dates: string[];
    totalOrders: number[];
    validOrders: number[];
    totalOrderCount: number;
    validOrderCount: number;
    completionRate: number;
  }>({
    dates: [],
    totalOrders: [],
    validOrders: [],
    totalOrderCount: 0,
    validOrderCount: 0,
    completionRate: 0,
  });

  // 销量 Top10 数据
  const [topDishData, setTopDishData] = useState<{
    names: string[];
    sales: number[];
  }>({
    names: [],
    sales: [],
  });

  // 获取所有报表数据
  const fetchData = async (dates: [Dayjs, Dayjs]) => {
    const [beginTime, endTime] = dates.map((d) => d.format('YYYY-MM-DD'));
    setLoading(true);

    try {
      // 1. 营业额
      const turnoverRes = await turnoverStatistics({ begin: beginTime, end: endTime });
      if (turnoverRes.data) {
        const data = turnoverRes.data as API.TurnoverReportVO;
        setTurnoverData({
          dates: data.dateList?.split(',') || [],
          amounts: (data.turnoverList?.split(',') || []).map(Number),
        });
      }

      // 2. 用户增长
      const userRes = await userStatistics({ begin: beginTime, end: endTime });
      if (userRes.data) {
        const data = userRes.data as API.UserReportVO;
        setUserData({
          dates: data.dateList?.split(',') || [],
          users: (data.totalUserList?.split(',') || []).map(Number),
          newUsers: (data.newUserList?.split(',') || []).map(Number),
        });
      }

      // 3. 订单状态
      const orderRes = await orderStatistics({ begin: beginTime, end: endTime });
      if (orderRes.data) {
        const data = orderRes.data as API.OrderReportVO;
        setOrderData({
          dates: data.dateList?.split(',') || [],
          totalOrders: (data.orderCountList?.split(',') || []).map(Number),
          validOrders: (data.validOrderCountList?.split(',') || []).map(Number),
          totalOrderCount: data.totalOrderCount || 0,
          validOrderCount: data.validOrderCount || 0,
          completionRate: data.orderCompletionRate || 0,
        });
      }

      // 4. 销量 Top10
      const top10Res = await salesTop10Report({ begin: beginTime, end: endTime });
      if (top10Res.data) {
        const data = top10Res.data as any as API.SalesTop10ReportVO;
        setTopDishData({
          names: data.nameList?.split(',') || [],
          sales: (data.numberList?.split(',') || []).map(Number),
        });
      }
    } catch (error) {
      console.error('获取报表数据失败:', error);
    } finally {
      setLoading(false);
    }
  };

  // 默认加载最近7天数据

  // 默认加载最近7天数据
  useEffect(() => {
    const defaultRange = [moment().subtract(7, 'days'), moment()] as [Dayjs, Dayjs];
    setTimeRange(defaultRange);
    fetchData(defaultRange);
  }, []);

  return (
    <Spin spinning={loading}>
      <div style={{ padding: 24 }}>
        <h2>营收统计</h2>

        {/* 时间筛选 */}
        <DatePicker.RangePicker
          value={timeRange || undefined}
          onChange={(dates) => {
            if (dates && dates[0] && dates[1]) {
              setTimeRange(dates as [Dayjs, Dayjs]);
              fetchData(dates as [Dayjs, Dayjs]);
            }
          }}
          style={{ marginBottom: 24 }}
        />

        {/* 营业额柱状图 */}
        <Row gutter={16} style={{ marginBottom: 24 }}>
          <Col span={24}>
            <Card title="时间段营业额">
              <ReactECharts
                option={{
                  tooltip: { trigger: 'axis' },
                  xAxis: { type: 'category', data: turnoverData.dates },
                  yAxis: { type: 'value' },
                  series: [
                    {
                      name: '营业额',
                      type: 'bar',
                      data: turnoverData.amounts,
                      itemStyle: { color: '#5470c6' },
                    },
                  ],
                }}
              />
            </Card>
          </Col>
        </Row>

        {/* 用户趋势 + 订单分布 */}
        <Row gutter={16} style={{ marginBottom: 24 }}>
          <Col span={12}>
            <Card title="用户增长趋势">
              <ReactECharts
                option={{
                  tooltip: { trigger: 'axis' },
                  legend: { data: ['总用户', '新增用户'] },
                  xAxis: { type: 'category', data: userData.dates },
                  yAxis: { type: 'value' },
                  series: [
                    {
                      name: '总用户',
                      type: 'line',
                      data: userData.users,
                      itemStyle: { color: '#91cc75' },
                    },
                    {
                      name: '新增用户',
                      type: 'line',
                      data: userData.newUsers,
                      itemStyle: { color: '#fac858' },
                    },
                  ],
                }}
              />
            </Card>
          </Col>

          <Col span={12}>
            <Card title="总订单 vs 有效订单">
              <ReactECharts
                option={{
                  tooltip: { trigger: 'item' },
                  legend: { orient: 'vertical', right: 10, top: 30 },
                  series: [
                    {
                      name: '订单统计',
                      type: 'pie',
                      radius: ['40%', '70%'],
                      avoidLabelOverlap: false,
                      label: { show: false },
                      data: [
                        { value: orderData.totalOrderCount, name: '总订单' },
                        { value: orderData.validOrderCount, name: '有效订单' },
                      ],
                      itemStyle: {
                        borderRadius: 5,
                        borderColor: '#fff',
                        borderWidth: 2,
                      },
                    },
                  ],
                }}
              />
            </Card>
          </Col>
        </Row>
        <Row gutter={16} style={{ marginBottom: 24 }}>
          <Col span={12}>
            <Card title="订单完成率">
              <ReactECharts
                option={{
                  tooltip: { formatter: '{a}<br/>{b}: {c}%' },
                  series: [
                    {
                      name: '完成率',
                      type: 'gauge',
                      detail: { formatter: `{value}%` },
                      data: [{ value: orderData.completionRate, name: '完成率' }],
                      splitLine: { lineStyle: { width: 3 } },
                      axisLine: {
                        lineStyle: {
                          width: 8,
                          color: [[1, '#5470C6']],
                        },
                      },
                    },
                  ],
                }}
              />
            </Card>
          </Col>
        </Row>
        <Row gutter={16} style={{ marginBottom: 24 }}>
          <Col span={24}>
            <Card title="每日订单趋势">
              <ReactECharts
                option={{
                  tooltip: { trigger: 'axis' },
                  legend: { data: ['总订单', '有效订单'] },
                  xAxis: {
                    type: 'category',
                    data: orderData.dates,
                  },
                  yAxis: { type: 'value' },
                  series: [
                    {
                      name: '总订单',
                      type: 'bar',
                      stack: '总量',
                      data: orderData.totalOrders,
                      itemStyle: { color: '#91cc75' },
                    },
                    {
                      name: '有效订单',
                      type: 'bar',
                      stack: '总量',
                      data: orderData.validOrders,
                      itemStyle: { color: '#fac858' },
                    },
                  ],
                }}
              />
            </Card>
          </Col>
        </Row>

        {/* 销量 Top10 */}
        <Row gutter={16}>
          <Col span={24}>
            <Card title="销量 Top10 菜品">
              <ReactECharts
                option={{
                  tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
                  xAxis: { type: 'value' },
                  yAxis: { type: 'category', data: topDishData.names, axisLabel: { rotate: 45 } },
                  series: [
                    {
                      name: '销量',
                      type: 'bar',
                      data: topDishData.sales,
                      itemStyle: { color: '#ee6666' },
                    },
                  ],
                }}
              />
            </Card>
          </Col>
        </Row>
      </div>
    </Spin>
  );
};

export default RevenuePage;
